<?php

namespace Portal\Api;

use Portal\Common\DataApi as Api;
use Portal\Domain\Admin as AdminDomain;
use PhalApi\Exception\BadRequestException;
use PhalApi\Exception\InternalServerErrorException;

/**
 * 后台用户管理
 * @author chenwengen 20240420
 */
class Admin extends Api
{
    public function getRules()
    {
        return array(
            'getData' => array(
                'id' => array('name' => 'id', 'type' => 'int', 'require' => true, 'min' => 1, 'desc' => 'ID'),
            ),
            'tableList' => array(
                'page' => array('name' => 'pageNum', 'type' => 'int', 'default' => 1, 'min' => 1, 'desc' => '页码'),
                'limit' => array('name' => 'pageSize', 'type' => 'int', 'default' => 10, 'min' => 1, 'max' => 100, 'desc' => '每页记录数'),
                'searchParams' => array('name' => 'searchParams', 'type' => 'array', 'format' => 'json', 'default' => array(), 'desc' => \PhalApi\T('search params')),
                'keywords' => array('name' => 'keywords', 'type' => 'string','require' => false, 'desc' => '关键字(用户名/昵称/手机号)'),
                'status' => array('name' => 'status','require' => false, 'type' => 'enum',  'range' => array('0', '1'), 'desc' => '用户状态((1:正常;0:禁用))'),
                'dept_id' => array('name' => 'deptId','require' => false, 'type' => 'int','desc' => '部门id'),
                'role_ids' => array('name' => 'roleIds','require' => false, 'type' => 'array', 'desc' => '角色ID列表，逗号分隔'),
                'createTime' => array('name' => 'createTime', "type" => "array",'require' => false, 'desc' => '创建开始时间'),
                'field' => array('name' => 'field', 'require' => false, 'default' => 'id', 'desc' => '排序的字段'),
                'direction' => array('name' => 'direction','require' => false, 'type' => 'enum','default' => "ASC", 'range' => array('ASC', 'DESC'), 'desc' => '排序方向 (ASC/DESC)'),
            ),
            'createData' => array(
                 'username' => array('name' => 'username', 'type' => 'string',  'require' => true, 'desc' => '用户名'),
                 'nickname' => array('name' => 'nickname', 'type' => 'string',  'require' => true, 'desc' => '用户昵称'),
                'role_ids' => array('name' => 'roleIds','require' => true, 'type' => 'array', 'desc' => '角色ID列表，逗号分隔'),
                 'mobile' => array('name' => 'mobile','type' => 'string','require' => false, 'regex' => "/^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/",'desc' => '手机号'),
                 'gender' => array('name' => 'gender','require' => false, 'type' => 'enum', 'range' => array('0', '1', '2'), 'desc' => '性别' ),
                 'avatar' => array('name' => 'avatar','type' => 'string','require' => false,'regex' => "/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i",'desc' => '头像'),
                 'email' => array('name' => 'email','type' => 'string','require' => false,'regex' => "/^\S+@\S+\.\S+$/",'desc' => '邮箱'),
                 'status' => array('name' => 'status', 'type' => 'enum', 'require' => false,"default" => 1,'range' => array('0', '1'),'desc' => '状态'),
                 'dept_id' => array('name' => 'deptId','type' => 'int','require' => false, 'type' => 'callback', 'callback' => 'Portal\\Api\\Dept::deptList', 'desc' => '部门id'),
                 'openid' => array('name' => 'openId', 'type' => 'string', 'default' => "", 'require' => false, 'desc' => '微信openId'),
                ),
            'deleteData' => array(
                'id' => array('name' => 'id', 'require' => true, 'type' => 'int', 'min' => 1, 'desc' => \PhalApi\T('ID to delete')),
            ),
            'deleteDataIDs' => array(
                'ids' => array('name' => 'ids', 'type' => 'array', 'format' => 'explode', 'seperator' => ',', 'require' => true, 'desc' => \PhalApi\T('ids to delete'))
            ),
            'updateData' => array(
                'id' => array('name' => 'id', 'type' => 'int', 'require' => true, 'min' => 1, 'desc' => 'ID'),
                'status' =>  array('name' => 'status', 'type' => 'enum', 'require' => false,'range' => array('0', '1'),'desc' => '状态'),
                'role_ids' => array('name' => 'roleIds', 'require' => true, 'type' => 'callback', 'callback' => 'Portal\\Api\\Role::roleIdList','desc' => '角色ID集合'),
                'nickname' => array('name' => 'nickname', 'type' => 'string',  'require' => true, 'desc' => '用户昵称'),
                'username' => array('name' => 'username', 'type' => 'string',  'require' => true, 'desc' => '用户名'),
                'avatar' => array('name' => 'avatar', 'type' => 'string',  'require' => false, 'desc' => '用户头像'),
                'dept_id' => array('name' => 'deptId','type' => 'int','require' => false,'type' => 'callback', 'callback' => 'Portal\\Api\\Dept::deptList', 'desc' => '部门id'),
                'gender' => array('name' => 'gender','require' => false, 'type' => 'enum', 'range' => array('0', '1', '2'), 'desc' => '性别' ),
                'mobile' => array('name' => 'mobile','type' => 'string','require' => false, 'regex' => "/^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/",'desc' => '手机号'),
                'email' => array('name' => 'email','type' => 'string','require' => false,'regex' => "/^\S+@\S+\.\S+$/",'desc' => '邮箱'),
              ),
               'updateProfile' => array(
                'nickname' => array('name' => 'nickname', 'type' => 'string',  'require' => false, 'desc' => '用户昵称'),
                'avatar' => array('name' => 'avatar', 'type' => 'string',  'require' => false, 'desc' => '用户头像'),
                'gender' => array('name' => 'gender','require' => false, 'type' => 'enum', 'range' => array('0', '1', '2'), 'desc' => '性别' ),
                'mobile' => array('name' => 'mobile','type' => 'string','require' => false, 'regex' => "/^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/",'desc' => '手机号'),
                'email' => array('name' => 'email','type' => 'string','require' => false,'regex' => "/^\S+@\S+\.\S+$/",'desc' => '邮箱'),
              ),
            'resetPassword' => array(
                'id' => array('name' => 'id', 'type' => 'int', 'require' => true, 'min' => 1, 'desc' => '用户id',),
                'password' => array('name' => 'password', 'type' => 'string', 'require' => true, 'min' => 6, 'desc' => '密码',),
              ),
            'alterPassword' => array(
                'oldPassword' => array('name' => 'oldPassword', 'type' => 'string', 'require' => true, 'min' => 6, 'desc' => '原密码',),
                'newPassword' => array('name' => 'newPassword', 'type' => 'string', 'require' => true, 'min' => 6, 'desc' => '新密码',),
              ),
              'export' => array(
                'page' => array('name' => 'pageNum', 'type' => 'int', 'default' => 1, 'min' => 1, 'desc' => '页码'),
                'limit' => array('name' => 'pageSize', 'type' => 'int', 'default' => 10, 'min' => 1, 'max' => 100, 'desc' => '每页记录数'),
                'searchParams' => array('name' => 'searchParams', 'type' => 'array', 'format' => 'json', 'default' => array(), 'desc' => \PhalApi\T('search params')),
                'keywords' => array('name' => 'keywords', 'type' => 'string','require' => false, 'desc' => '关键字(用户名/昵称/手机号)'),
                'status' => array('name' => 'status','require' => false, 'type' => 'enum',  'range' => array('0', '1'), 'desc' => '用户状态((1:正常;0:禁用))'),
                'deptId' => array('name' => 'deptId','require' => false, 'type' => 'callback', 'callback' => 'Portal\\Api\\Dept::deptList', 'desc' => '部门id'),
                'startTime' => array('name' => 'startTime', 'require' => false, 'type' => 'date', 'format' => 'timestamp', 'desc' => '创建开始时间'),
                'endTime' => array('name' => 'endTime', 'require' => false, 'type' => 'date', 'format' => 'timestamp', 'desc' => '创建结束时间'),
              ),
              'import' => array(
                  'dept_id' => array('name' => 'deptId','require' => true, 'type' => 'callback', 'callback' => 'Portal\\Api\\Dept::deptList', 'desc' => '部门id'),
                    'file' => array(
                    'name' => 'file',        // 客户端上传的文件字段
                    'type' => 'file',
                    'require' => true,
                    'max' => 2097152,        // 最大允许上传2M = 2 * 1024 * 1024,
                    'range' => array('application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/wps-office.xlsx'),  // 允许的文件格式
                    'ext' => 'xls,xlsx', // 允许的文件扩展名
                    'desc' => '待上传的excel文件',
                ),
                ),
        'status' => array(
                'id' => array('name' => 'userId', 'type' => 'int', 'require' => true, 'min' => 1, 'desc' => 'ID'),
                'status' =>  array('name' => 'status', 'type' => 'enum', 'require' => true,'range' => array('0', '1'),'desc' => '状态'),
        ),
        );
    }
    protected function getDataModel()
    {
        return  new \Portal\Model\Admin();
    }
    // protected function userCheck()
    // {
    // }

    /**
     * 获取当前登录用户信息
     * @desc 获取当前登录用户信息
     * @exception 403 用户信息不存在
     * @return object|null 数据
     */
    public function getMeData()
    {
        $userId = \PhalApi\DI()->admin->getId();
        $adminDomain = new AdminDomain();
        $returnData = $adminDomain->getInfo($userId);
        if ($returnData === false) {
            throw new BadRequestException("用户信息不存在", 3);
        }
        return $returnData;
    }
    /**
     * 用户表单数据
     * @desc 用户表单数据
     * @exception 403 没有权限操作
     * @return object|null 数据
     */
    public function getData()
    {
        $this->permissionRequired(["sys:user:edit"]);
        //除了超级管理员，管理员外，只能查看自己信息
        $where = array('id' => $this->id);
        $whereParams = array();
        $select = $this->getDataSelect();

        // 前置条件加工
        $where = $this->getGetDataWhere($where);
        $model = $this->getDataModel();
        $data = $model->getData($where, $whereParams, $select);
        if (!$data) {
            throw new BadRequestException("信息不存在", 4);
        }
        $data = $this->afterGetData($data);

        return $this->returnDataResult($data);
    }
    /**
     * 获取个人中心用户信息
     * @desc 获取个人中心用户信息
     * @exception 403 没有权限操作
     * @return object|null 数据
     */
    public function profile()
    {
        $userId = \PhalApi\DI()->admin->getId();
        $where = array('id' => $userId);
        $whereParams = array();
        $select = ['id','username','nickname','avatar','gender','mobile','email','dept_id','create_time'];
        // 前置条件加工
        $where = $this->getGetDataWhere($where);
        $model = $this->getDataModel();
        $data = $model->getData($where, $whereParams, $select);
        if (!$data) {
            throw new BadRequestException("信息不存在", 4);
        }
        $data = $this->afterGetProfileData($data);
        return $this->returnDataResult($data);
    }


    // 获取单个数据时需要返回的字段
    protected function getDataSelect()
    {
        return '*';
    }

    // 前置条件加工
    protected function getGetDataWhere($where)
    {
        return $where;
    }

    // 取到数据后的加工处理
    protected function afterGetProfileData($data)
    {
        if (isset($data['dept_id'])) {
            $deptDomain = new \Portal\Domain\Dept();
            $data['deptName'] = $deptDomain->getDeptName($data['dept_id']);
            unset($data['dept_id']);
        }
        if (isset($data['create_time'])) {
            $data['createTime'] = date('Y-m-d H:i:s', $data['create_time']);
            unset($data['create_time']);
        }
        return $data;
    }
    protected function afterGetData($data)
    {
        if (isset($data['dept_id'])) {
            $data['deptId'] = $data['dept_id'];
            unset($data['dept_id']);
        }
        if (isset($data['id'])) {
            // $domainRole=new \Portal\Domain\Role();
            $adminRoleDomain = new \Portal\Domain\AdminRole();
            // $data['roleIds']= explode(',', $domainRole->getRoleNames($data['id']));
            $data['roleIds'] = $adminRoleDomain->getRoleIds($data['id']);
        }

        return $data;
    }
    /**
     * 用户分页列表
     * @desc 用户分页列表
    * @return array    list   列表数据
     * @return int      total   总数量
     */
    public function tableList()
    {
        $this->permissionRequired(["sys:user:query"]);
        $model = $this->getDataModel();
        $searchParams = array();
        foreach ($this->searchParams as $key => $val) {
            if ($val !==  '') {
                $searchParams[$key] = $val;
            }
        }
        // 条件
        $where = !empty($searchParams) ? $searchParams : null;
        $whereParams = array();
        $where = $this->getTableListWhere($where);
        $select = $this->getTableListSelect();
        $order = $this->getTableListOrder();
        $page = $this->page;
        $perpage = $this->limit;
        $total = $model->count($where);
        $items = $total > 0 ? $model->getList($where, $whereParams, $select, $order, $page, $perpage) : array();
        $items = $this->afterTableList($items);
        return $this->returnDataResult(array('total' => $total, 'list' => $items));
    }
    // 列表返回的字段
    protected function getTableListSelect()
    {
        return 'id,username,nickname,mobile,gender,avatar,email,status,dept_id,create_time';
    }

    // 列表的默认排序
    protected function getTableListOrder()
    {
        // return 'id DESC';
        return "$this->field $this->direction";
    }

    // 查询条件
    protected function getTableListWhere($where)
    {
        //获取没删除的用户
        $where['is_deleted'] = 0;
        if ($this->keywords !== null && trim($this->keywords) != '') {
            $where['username LIKE ? OR nickname LIKE ? OR mobile LIKE ?'] = array("%$this->keywords%","%$this->keywords%","%$this->keywords%");
        }
        if ($this->status !== null) {
            $where['status'] = $this->status;
        }
        if ($this->dept_id !== null) {
            $where['dept_id'] = $this->dept_id;

        }
        if ($this->createTime) {
            $where['create_time BETWEEN ? AND ?'] = array(strtotime($this->createTime[0]), strtotime($this->createTime[1]));
        }
        if ($this->role_ids) {
            //查询对应role_ids的用户id
            $adminRoleDomain = new \Portal\Domain\AdminRole();
            $useIds = $adminRoleDomain->getUserIdsByRoleIds($this->role_ids);
            //查询对应role_ids的用户id
            $where['id'] = $useIds;
            //查询对应role_ids的用户id
        }
        //查看数据权限
        $viewableUsers = $this->dataPermissionRequired("select");
        if ($viewableUsers != 'all') {
            //全部之前的id
            //过滤不在所选择的部门id的内容
            if (isset($where['id'])) {
                //获取与角色查询数组的交集
                $where['id'] = array_merge(array_intersect($where['id'], $viewableUsers));
            } else {
                $where['id'] = $viewableUsers;
            }
        }

        //查看数据权限
        return $where;
    }

    // 取到列表数据后的加工处理
    protected function afterTableList($items)
    {
        $deptDomain = new \Portal\Domain\Dept();
        $roleDomain = new \Portal\Domain\Role();
        $adminRoleDomain = new \Portal\Domain\AdminRole();
        foreach ($items as $key => $item) {
            if (isset($item['create_time'])) {
                $item['createTime'] = date('Y-m-d H:i:s', $item['create_time']);
                unset($item['create_time']);
            }
            if (isset($item['dept_id'])) {
                $item['deptName'] = $deptDomain->getDeptName($item['dept_id']);
                unset($item['dept_id']);
            }
            if (isset($item['id'])) {
                $item['roleNames'] = $roleDomain->getRoleNames($item['id']);
                $item['roleIds'] = $adminRoleDomain->getRoleIds($item['id']);
            }
            $items[$key] = $item;
        }
        return $items;
    }
    /**
    * 新增用户
    * @desc 新增用户
    * @return int id 新纪录的ID
    * @exception 401 用户已经存在
    */
    public function createData($import = false)
    {

        $this->permissionRequired(["sys:user:add"]);
        //不是文件导入
        if (!$import) {
            //获取当前
            $array_keys = array_keys($this->getApiRules());
            $newData = [];
            foreach ($array_keys as $key) {
                if ($this->$key !== null) {
                    $newData[$key] = $this->$key;
                }
            }
        } else {
            //文件导入新增用户
            $array_keys = ['username','nickname','gender','mobile','email','roleIds','dept_id'];
            $newData = [];
            foreach ($array_keys as $key) {
                if ($this->$key !== null) {
                    $newData[$key] = $this->$key;
                }
            }
        }

        $model = $this->getDataModel();
        $checkUserName = $this->getDataModel()::notorm()->select('id')->where(['username' => $this->username])->fetchOne();
        if ($checkUserName) {
            //用户存在
            throw new BadRequestException('用户已经存在！', 1);
        }

        // $newData = $this->newData;
        // 检测必传字段
        foreach ($this->createDataRequireKeys() as $key) {
            if (!isset($newData[$key]) || $newData[$key] === '') {
                throw new BadRequestException(\PhalApi\T('{name} require, but miss', array('name' => $key)));
            }
        }
        // 排除字段
        foreach ($this->createDataExcludeKeys() as $key) {
            unset($newData[$key]);
        }

        // 更多初始化的字段数据
        $newData = $this->beforeCreateData($newData);

        if (empty($newData)) {
            throw new BadRequestException(\PhalApi\T('miss post data'));
        }

        $id = 0;
        try {
            $id = $model->insert($newData);
            //添加到权限表
            if (intval($id) > 0) {
                $insertDatas = [];
                foreach ($this->role_ids as $roleId) {
                    $insertDatas[] = ['user_id' => $id,'role_id' => $roleId];
                }
                if (!empty($insertDatas)) {
                    $adminRoleModel = new \Portal\Model\AdminRole();
                    $adminRoleModel->insertMore($insertDatas);
                }
            }
        } catch (\PDOException $ex) {
            throw new BadRequestException(\PhalApi\DI()->debug ? $ex->getMessage() : \PhalApi\T('system error, please contact engeneer'));
        }

        return $this->returnDataResult(array('id' => intval($id)));
    }
    // 必须提供的字段
    protected function createDataRequireKeys()
    {
        return array('username','nickname','role_ids');
    }

    // 不允许客户端写入的字段
    protected function createDataExcludeKeys()
    {
        return array();
    }

    // 创建时更多初始化的数据
    protected function beforeCreateData($newData)
    {
        if (isset($newData['role_ids'])) {
            unset($newData['role_ids']);
        }
        $salt = \PhalApi\Tool::createRandStr(64);
        $newData['salt'] = $salt;
        $newData['create_time'] = time();
        $newData['update_time'] = $newData['create_time'];
        $newData['create_by'] = \PhalApi\DI()->admin->getId();
        //判断当前用户是否有权限添加root
        return $newData;
    }
    /**
    * 更新数据
    * @desc 通用数据接口，根据ID更新单条数据
    * @return int|boolean updated_num 更新的数据条数，0表示无更新，1表示更新成功
    */
    public function updateData()
    {
        $this->permissionRequired(["sys:user:edit"]);
        $model = $this->getDataModel();
        //获取当前
        $array_keys = array_keys($this->getApiRules());

        $updateData = [];
        foreach ($array_keys as $key) {
            if ($this->$key !== null && $key !== 'data') {
                $updateData[$key] = $this->$key;
            }
        }
        // $updateData = $this->data;
        unset($updateData['id']);
        foreach ($this->updateDataRequireKeys() as $key) {
            if (!isset($updateData[$key]) || $updateData[$key] === '') {
                throw new BadRequestException(\PhalApi\T('{name} require, but miss', array('name' => $key)));
            }
        }
        foreach ($this->updateDataExcludeKeys() as $key) {
            unset($updateData[$key]);
        }

        if (empty($updateData)) {
            throw new BadRequestException(\PhalApi\T('miss update data'));
        }

        $updateData = $this->beforeUpdateData($updateData);
        try {
            $where = array('id' => $this->id);
            $where = $this->getUpdateDataWhere($where);
            //更新之前获取角色当前更改用户的
            $oldRoleIds = [];
            $adminRoleDomain = new \Portal\Domain\AdminRole();
            $oldRoleIds = $adminRoleDomain->getRoleIds($this->id);

            // echo json_encode($this->roleIds);
            // echo json_encode($oldRoleIds);
            // var_dump($this->roleIds == $oldRoleIds);
            // exit();
            $rows = $model->updateAll($where, $updateData);
            if ($rows && $this->role_ids != $oldRoleIds) {
                //更新成功 //并且有修改相关权限内容 更新权限表对应数据
                $newRoleIds = $this->role_ids;
                //更新新的权限表
                $adminRoleDomain->updateRoleIds($this->id, $oldRoleIds, $newRoleIds);
            }
            return $this->returnDataResult(array('updated_num' => $rows));
        } catch (\PDOException $ex) {
            throw new BadRequestException(\PhalApi\DI()->debug ? $ex->getMessage() : \PhalApi\T('system error, please contact engeneer'));
        }
    }
    /**
    * 更新个人中心数据
    * @desc 更新个人中心数据
    * @return int|boolean updated_num 更新的数据条数，0表示无更新，1表示更新成功
    */
    public function updateProfile()
    {
        $this->id = \PhalApi\DI()->admin->getId();
        $model = $this->getDataModel();
        $array_keys = array_keys($this->getApiRules());
        $updateData = [];
        foreach ($array_keys as $key) {
            if ($this->$key !== null && $key !== 'data') {
                $updateData[$key] = $this->$key;
            }
        }
        unset($updateData['id']);
        foreach ($this->updateDataRequireKeys() as $key) {
            if (!isset($updateData[$key]) || $updateData[$key] === '') {
                throw new BadRequestException(\PhalApi\T('{name} require, but miss', array('name' => $key)));
            }
        }
        foreach ($this->updateDataExcludeKeys() as $key) {
            unset($updateData[$key]);
        }

        if (empty($updateData)) {
            throw new BadRequestException(\PhalApi\T('miss update data'));
        }

        $updateData = $this->beforeProfileUpdateData($updateData);
        try {
            $where = array('id' => $this->id);
            $where = $this->getUpdateDataWhere($where);
            $rows = $model->updateAll($where, $updateData);
            return $this->returnDataResult(array('updated_num' => $rows));
        } catch (\PDOException $ex) {
            throw new BadRequestException(\PhalApi\DI()->debug ? $ex->getMessage() : \PhalApi\T('system error, please contact engeneer'));
        }
    }
    // 更新时必须提供的字段
    protected function updateDataRequireKeys()
    {
        return array();
    }

    // 更新时不允许更新的字段
    protected function updateDataExcludeKeys()
    {
        return array('id','username','password','salt','create_time','update_time','update_by');
    }

    // 获取更新数据的条件
    protected function getUpdateDataWhere($where)
    {
        return $where;
    }

    // 在更新数据前的处理
    protected function beforeUpdateData($updateData)
    {
        //检查是否有权限更新当前数据
        $hasPermission = $this->dataPermissionRequired("update", $this->id);
        if (!$hasPermission) {
            throw new BadRequestException('您没有权限修改此用户状态', 3);
        }
        if (isset($updateData['role_ids'])) {
            unset($updateData['role_ids']);
        }
        //获取要更新
        $updateData['update_time'] = time();
        $updateData['update_by'] = \PhalApi\DI()->admin->getId();
        //检查修改状态权限
        $this->updateStatus($updateData);
        //检查修改状态权限
        return $updateData;
    }
    protected function beforeProfileUpdateData($updateData)
    {
        //获取要更新
        $updateData['update_time'] = time();
        $updateData['update_by'] = \PhalApi\DI()->admin->getId();
        return $updateData;
    }
    /**
    * 修改用户自己密码
    * @desc 修改用户自己密码
    * @return bool true
    * @exception 403 超级管理员才有修改密码权限
    */
    public function alterPassword()
    {
        $oldPassword = $this->oldPassword;
        $newPassword = $this->newPassword;
        $userId = \PhalApi\DI()->admin->getId();
        $domainAdmin = new AdminDomain();
        $flag = $domainAdmin->alertPassword($userId, $oldPassword, $newPassword);
        return $flag;
    }
    /**
    * 重置密码
    * @desc 重置密码
    * @return bool true
    * @exception 403 超级管理员才有修改密码权限
    */
    public function resetPassword()
    {
        $this->permissionRequired(["sys:user:reset-password"]);
        $id = $this->id;
        $password = $this->password;
        $domainAdmin = new AdminDomain();
        $flag = $domainAdmin->resetPassword($id, $password);
        return $flag;
    }


    /**
      *删除用户
      * @desc 删除用户
      */
    public function deleteData()
    {
        // $this->permissionRequired(["sys:user:delete"]);
        // $where = array('id' => $this->id);
        // $model = $this->getDataModel();
        // // $rows = !empty($where) ? $model->deleteAll($where) : 0;
        // $rows = !empty($where) ? $model->updateAll($where, ['is_deleted' => 1]) : 0;
        // //删除权限表中的数据
        // // \Portal\Model\AdminRole::notorm()->where(['user_id' => $this->id])->delete();
        // return $this->returnDataResult(array('deleted_num' => $rows));
        $this->ids = [$this->id];
        $this->deleteDataIDs();
    }

    // 删除数据的条件加工
    protected function getDeleteDataWhere($where)
    {
        return $where;
    }

    /**
     * 批量删除用户
     * @desc 批量删除用户
     */
    public function deleteDataIDs()
    {

        # 获取当前用户ID，避免自己删除自己
        $currentUserId = \PhalApi\DI()->admin->getId();
        if (in_array($currentUserId, $this->ids)) {
            throw new BadRequestException("不能删除当前登陆用户", 3);
        }
        //检查是否有删除权限菜单功能
        $this->permissionRequired(["sys:user:delete"]);
        //检查是否有删除对应用户id的权限功能
        $authorizedIds = [];
        $unAuthorizedIds = [];
        foreach ($this->ids as $id) {
            $hasPermission = $this->dataPermissionRequired("delete", $id);
            if ($hasPermission) {
                $authorizedIds[] = $id;
            } else {
                $unAuthorizedIds[] = $id;
            }
        }
        if (!empty($unAuthorizedIds)) {
            throw new BadRequestException("您没有权限删除以下用户".implode(',', $unAuthorizedIds), 3);
        }
        $model = $this->getDataModel();
        //查找所有要删除的用户
        $allUserDatas = $model::notorm()->select("id")->where(['is_deleted' => 0])->fetchAll();
        $findIds = [];
        foreach ($allUserDatas as $userData) {
            $findIds[] = $userData['id'];
        }
        $checkIds = array_diff($this->ids, $findIds);
        if (!empty($checkIds)) {
            throw new BadRequestException("用户id不存在或已经删除".implode(',', $checkIds), 3);
        }
        $rows = $this->ids ? $model->updateAll(['id' => $this->ids], ['is_deleted' => 1]) : 0;
        //删除权限表中的数据
        // \Portal\Model\AdminRole::notorm()->where(['user_id' => $this->ids])->delete();
        return $this->returnDataResult(array('deleted_num' => $rows));
    }
    /**
     * 导出用户
     * @desc 导出用户
     */
    public function export()
    {
        $this->permissionRequired(["sys:user:export"]);
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);
        //设置第一格单元格高度为25
        $spreadsheet->getActiveSheet()->getDefaultRowDimension("1")->setRowHeight(25);
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->setTitle('用户列表');
        $header = [
          'A1' => '用户名',
          'B1' => '用户昵称',
          'C1' => '部门',
          'D1' => '性别',
          'E1' => '手机号码',
          'F1' => '邮箱',
          'G1' => '创建时间'
        ];
        $styleArray = [
    'font' => [
        'bold' => true,
         'color' => [
                     'rgb' => '000000',
                ]
    ],

    'alignment' => [
        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
         'vertical' =>  \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
      ],
];
        //设置单元格样式

        foreach ($header as $key => $headerItem) {
            $worksheet->getStyle($key)->applyFromArray($styleArray)->getFont()->setSize(14);
            $worksheet->getStyle($key)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('CCCCCC');
            $worksheet->setCellValue($key, $headerItem);
        }
        //表头
        //设置单元格内容
        $model = $this->getDataModel();

        $searchParams = array();
        foreach ($this->searchParams as $key => $val) {
            if ($val !==  '') {
                $searchParams[$key] = $val;
            }
        }
        // 条件
        $where = !empty($searchParams) ? $searchParams : null;
        $whereParams = array();
        $where = $this->getTableListWhere($where);
        $select = $this->getTableListSelect();
        $order = $this->getTableListOrder();
        $page = $this->page;
        $perpage = $this->limit;
        $total = $model->count($where);
        $items = $total > 0 ? $model->getList($where, $whereParams, $select, $order, $page, $perpage) : array();
        $items = $this->afterTableList($items);
        $titleKey = [
          'username' => 1,
          'nickname' => 2,
          'deptName' => 3,
          'genderLabel' => 4,
          'mobile' => 5,
          'email' => 6,
          'createTime' => 7,
        ];
        $styleArray = [
    'font' => [
         'color' => [
                     'rgb' => '000000',
                ]
    ],

    'alignment' => [
        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
         'vertical' =>  \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
      ],
];
        if (is_array($items) && !empty($items)) {
            foreach ($items as $index => $item) {
                $currentIndex = $index + 2;
                foreach ($item as $key => $r) {
                    if (isset($titleKey[$key])) {
                        $titleKeyVal = $titleKey[$key];
                        //设置样式
                        $worksheet->getStyle([$titleKeyVal, $currentIndex])->applyFromArray($styleArray);
                        $worksheet->setCellValue([$titleKeyVal, $currentIndex], $r ? $r : '');
                    }
                }
            }
        }
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.trim(urlencode('用户列表'), '_').'"');
        header('Cache-Control: max-age=0');
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save('php://output');
        flush();
        exit;
    }

    /**
       * 用户导入模板下载
       * @desc 用户导入模板下载
       */
    public function template()
    {
        $localFileName = API_ROOT . DIRECTORY_SEPARATOR . 'public'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'user_template.xlsx';
        // 下载Excel文件
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.trim(urlencode('用户导入模板'), '_').'".xlsx');
        header('Content-Length: ' . filesize($localFileName));
        readfile($localFileName);
        flush();
        exit;
    }
    /**
         * 导入用户
         * @desc 导入用户
         */
    public function import()
    {
        $this->permissionRequired(["sys:user:import"]);
        $tmpName = $this->file['tmp_name'];
        $name = md5($this->file['name'] . $_SERVER['REQUEST_TIME']);
        $ext = strrchr($this->file['name'], '.');
        $uploadFolder = sprintf('%s/public/uploads/', API_ROOT);
        if (!is_dir($uploadFolder)) {
            mkdir($uploadFolder, 0777);
        }

        $filePath = $uploadFolder .  $name . $ext;
        if (move_uploaded_file($tmpName, $filePath)) {
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filePath);
            $worksheet = $spreadsheet->getActiveSheet();
            // 遍历工作表中的每一行和每一列
            $insertDatas = [];
            foreach ($worksheet->getRowIterator() as $key => $row) {
                if ($key < 2) {
                    continue;
                }
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false);
                $insertData = [];
                $roleDomain = new \Portal\Domain\Role();
                $mobelPattern = '/^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/';
                foreach ($cellIterator as $k => $cell) {
                    // 获取单元格的数据
                    $value = $cell->getValue();
                    //判断必须数据
                    if ($k == 'A' && (trim($value) == '' || !$value)) {
                        throw new BadRequestException(\PhalApi\T('用户名不能为空!'));
                    }
                    if ($k == 'B' && (trim($value) == '' || !$value)) {
                        throw new BadRequestException(\PhalApi\T('昵称不能为空!'));
                    }
                    if ($k == 'F' && (trim($value) == '' || !$value)) {
                        throw new BadRequestException(\PhalApi\T('角色不能这空!'));
                    }
                    if ($k == 'D' && trim($value) != '' && !preg_match($mobelPattern, $value)) {
                        throw new BadRequestException(\PhalApi\T('手机号码格式不正确!'));
                    }
                    if ($k == 'E' && trim($value) != '' &&  !filter_var($value, FILTER_VALIDATE_EMAIL)) {
                        throw new BadRequestException(\PhalApi\T('邮箱格式不正确!'));
                    }
                    switch ($k) {
                        case 'A':
                            $insertData['username'] = $value;
                            break;
                        case 'B':
                            $insertData['nickname'] = $value;
                            break;
                        case 'C':
                            $gender = trim($value);
                            switch ($gender) {
                                case '男':
                                    $insertData['gender'] = 1;
                                    break;
                                case '女':
                                    $insertData['gender'] = 2;
                                    break;
                                    break;
                                case '未知':
                                    $insertData['gender'] = 0;
                                    break;
                                    break;
                            }
                            break;
                        case 'D':
                            $insertData['mobile'] = trim($value);
                            break;
                        case 'E':
                            $insertData['email'] = $value;
                            break;
                        case 'F':
                            $roleNames = explode(',', strtoupper($value));
                            if (is_array($roleNames) && !empty($roleNames)) {
                                foreach ($roleNames as $roleKey => $roleName) {
                                    $roleNames[$roleKey] = trim($roleName);
                                }
                                $insertData['roleIds'] = $roleDomain->getRoleIds($roleNames);
                            } else {
                                throw new BadRequestException(\PhalApi\T('角色值应为：ADMIN,GUEST!'));
                            }
                            if (!isset($insertData['roleIds']) || !$insertData['roleIds']) {
                                throw new BadRequestException(\PhalApi\T('角色值应为：ADMIN,GUEST!'));
                            }
                            break;
                    }
                    $insertData['dept_id'] = $this->dept_id;
                }
                $insertDatas[] = $insertData;
            }

            if (!empty($insertDatas)) {
                foreach ($insertDatas as $insertData) {
                    foreach ($insertData as $key => $field) {
                        $this->$key = $field;
                    }
                    $this->createData(true);
                }
            }
            $returnData = array('code' => 1);
            \PhalApi\DI()->response->setMsg('用户批量导入成功！');
            return $returnData;
        }
    }
    /**
           * 修改用户状态
           * @desc 修改用户状态
           */
    public function status()
    {
        $id = $this->id;
        $status = $this->status;
        # 不允许禁用自己
        if (\PhalApi\DI()->admin->getId() == $id && $status == "0") {
            throw new BadRequestException("不能禁用当前登陆用户", 3);
        }
        # 不允许禁用root用户
        if (\PhalApi\DI()->admin->getUserName() == 'root' && $status == "0") {
            throw new BadRequestException("不能禁用root用户", 3);
        }
        $this->permissionRequired(["sys:user:edit"]);
        $where['is_deleted'] = 1;
        $where['id'] = $this->id;
        $checkAdmin = $this->getDataModel()::notorm()->select('id')->where($where)->fetchOne();
        if ($checkAdmin) {
            throw new BadRequestException('用户不存在', 4);
        }
        $hasPermission = $this->dataPermissionRequired("update", $id);
        if (!$hasPermission) {
            throw new BadRequestException('您没有权限修改此用户状态', 3);
        }
        $returnData['code'] = 1;
        $this->getDataModel()->updateAll(['id' => $id], ['status' => $status]);
        return $returnData;
    }

    /**
     * 修改信息的时候检查是否有权限修改状态
     */
    private function updateStatus($updateData)
    {
        # 不允许禁用自己
        if (\PhalApi\DI()->admin->getId() == $this->id && $this->status == "0") {
            throw new BadRequestException("不能禁用当前登陆用户", 3);
        }
        # 不允许禁用root用户
        if ($updateData['username'] == 'root' && $this->status == "0") {
            throw new BadRequestException("不能禁用root用户", 3);
        }

    }

    /**
     * 注销
     * @desc 获取验证码
     * @exception 400 非法请求，参数传递错误
     */  //
    public function logout()
    {
        //获取当前jwt的过期时间
        $exp = \PhalApi\DI()->admin->exp;
        $now = time();
        $remainingSeconds = $exp - $now;
        if ($remainingSeconds <= 0) {
            $remainingSeconds = 0;
        }

        if ($remainingSeconds > 0) {
            # 将 token 存入 Redis 黑名单中，key 前缀 "blacklist_"
            // $redis = \PhalApi\DI()->cache->getRedis();
            $bearerToken = \PhalApi\DI()->request->getHeader('Authorization');
            list($tokenType, $token) = explode(' ', $bearerToken);
            $cacheKey = 'blacklist_'.$token;
            \PhalApi\DI()->cache->set($cacheKey, "1", $remainingSeconds);
        }
        return [];
    }
}
